<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>table 组件综合演示 - Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="//unpkg.com/layui@2.11.0/dist/css/layui.css" rel="stylesheet">
    <style>
        .navbar {
            display: none;
        }
    </style>
</head>

<body>
    <div class="layui-tabs layui-hide-v" id="demoTabs1">
        <ul class="layui-tabs-header">
            <li lay-id="aaa">体检套餐</li>
            <li lay-id="bbb">体检项目</li>
            <li lay-id="ccc">套餐类型</li>
        </ul>
        <div class="layui-tabs-body">
            <div class="layui-tabs-item" id="tab1Content">
                <div style="padding: 16px;">
                    <table class="layui-hide" id="test1" lay-filter="test1"></table>
                    <div id="demo-laypage1"></div>
                </div>
            </div>
            <div class="layui-tabs-item" id="tab2Content">
                <div style="padding: 16px;">
                    <table class="layui-hide" id="test2" lay-filter="test2"></table>
                    <div id="demo-laypage2"></div>
                </div>
            </div>
            <div class="layui-tabs-item" id="packageTypeContent">
                <div style="padding: 16px;">
                    <table class="layui-hide" id="test3" lay-filter="test3"></table>
                    <div id="demo-laypage3"></div>
                </div>
            </div>
        </div>
    </div>
    <script type="text/html" id="toolbarDemo">
        <!-- 这里去除了原来的按钮组代码，保留空的 toolbarDemo 模板 -->
    </script>
    <script type="text/html" id="toolDemo">
        <div class="layui-clear-space">
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
        </div>
    </script>
    <script src="//unpkg.com/layui@2.11.0/dist/layui.js"></script>
    <script>
        layui.use(['table', 'dropdown', 'laypage', 'tabs', 'form'], function () {
            var table = layui.table;
            var dropdown = layui.dropdown;
            var laypage = layui.laypage;
            var tabs = layui.tabs;
            var form = layui.form;

            // 定义表格渲染函数
            function renderTable(tableId, filter, url, title, pageId) {
                table.render({
                    elem: '#' + tableId,
                    url: url,
                    toolbar: '#toolbarDemo',
                    defaultToolbar: ['filter', 'exports', 'print', {
                        title: '提示',
                        layEvent: 'LAYTABLE_TIPS',
                        icon: 'layui-icon-tips',
                        onClick: function (obj) {
                            layer.alert('自定义工具栏图标按钮');
                        }
                    }],
                    height: 'full-35',
                    css: ['.layui-table-tool-temp{padding-right: 145px;}'].join(''),
                    cellMinWidth: 80,
                    totalRow: true,
                    page: true,
                    request: {
                        pageName: 'PageIndex',
                        limitName: 'PageSize'
                    },
                    limit: 15,
                    limits: [2, 4, 6, 10, 15, 20],
                    cols: getCols(title),
                    done: function (res, curr, count) {
                        laypage.render({
                            elem: pageId,
                            count: count,
                            curr: curr,
                            jump: function (obj, first) {
                                if (!first) {
                                    table.reload(tableId, {
                                        page: {
                                            curr: obj.curr
                                        }
                                    });
                                }
                            }
                        });
                    },
                    error: function (res, msg) {
                        console.log(res, msg)
                    }
                });
            }

            // 获取不同表格的列定义
            function getCols(title) {
                if (title === '体检套餐') {
                    return [[
                        { field: 'healthCheckPackageId', width: 80, sort: true, fixed: 'left', title: 'ID' },
                        { field: 'packageNo', width: 110, title: '体检套餐编号' },
                        { field: 'packageName', width: 110, title: '体检套餐名称' },
                        { field: 'packageType', title: '体检套餐类型', width: 110 },
                        { field: 'applicableToHospitals', width: 110, title: '适用院区' },
                        { field: 'packagePrice', width: 110, title: '套餐价格' },
                        { field: 'packages', width: 110, title: '套餐介绍' },
                        { field: 'courseDescription', width: 130, title: '套餐类型' },
                        {
                            field: 'offerstatus',
                            width: 100,
                            title: title + ' - 项目状态',
                            sort: true,
                            templet: function (d) {
                                return '<input type="checkbox" name="status" value="' + d.healthCheckPackageId + '" lay-skin="switch" lay-text="开启|关闭" lay-filter="switchStatus"' + (d.offerstatus? 'checked' : '') + '>';
                            }
                        },
                        { fixed: 'right', title: '操作', width: 134, minWidth: 125, templet: '#toolDemo' }
                    ]];
                } else if (title === '体检项目') {
                    return [[
                        { type: 'checkbox', fixed: 'left' },
                        { field: 'physicalExaminationItemsId', fixed: 'left', width: 80, title: 'ID', sort: true, totalRow: '合计：' },
                        { field: 'projectNo', width: 100, title: title + ' - 编号' },
                        { field: 'projectName', width: 100, title: title + ' - 项目名称' },
                        { field: 'projectPrice', width: 100, title: title + ' - 项目价格(元)' },
                        { field: 'affiliationPlan', width: 200, title: title + ' - 所属套餐' },
                        { field: 'projectIntroduction', width: 100, title: title + ' - 项目简介' },
                        { field: 'precautions', width: 100, title: title + ' - 注意事项' },
                        {
                            field: 'projectStatus',
                            width: 100,
                            title: title + ' - 项目状态',
                            sort: true,
                            templet: function (d) {
                                return '<input type="checkbox" name="status" value="' + d.physicalExaminationItemsId + '" lay-skin="switch" lay-text="开启|关闭" lay-filter="switchStatus"' + (d.projectStatus? 'checked' : '') + '>';
                            }
                        },
                        { fixed: 'right', title: '操作', width: 134, minWidth: 125, templet: '#toolDemo' }
                    ]];
                } else if (title === '套餐类型') {
                    return [[
                        { type: 'checkbox', fixed: 'left' },
                        { field: 'packageTypeId', fixed: 'left', width: 80, title: 'ID', sort: true, totalRow: '合计：' },
                        { field: 'projectName', width: 100, title: title + ' - 类型名称' },
                        { field: 'packageNum', width: 100, title: title + ' - 套餐数量' },
                        { field: 'packagesAreIncluded', width: 200, title: title + ' - 包含套餐' },
                        {
                            field:'status',
                            width: 100,
                            title: title + ' - 状态',
                            sort: true,
                            templet: function (d) {
                                return '<input type="checkbox" name="status" value="' + d.packageTypeId + '" lay-skin="switch" lay-text="开启|关闭" lay-filter="switchStatus"' + (d.status ? 'checked' : '') + '>';
                            }
                        },
                        { fixed: 'right', title: '操作', width: 134, minWidth: 125, templet: '#toolDemo' }
                    ]];
                }
            }

            // 初始渲染三个表格
            renderTable('test1', 'test1', 'https://localhost:7171/api/HealthCheckPackage/GetHealthCheckPackage', '体检套餐', 'demo-laypage1');
            renderTable('test2', 'test2', 'https://localhost:7171/api/PhysicalExaminationItems', '体检项目', 'demo-laypage2');
            renderTable('test3', 'test3', 'https://localhost:7171/api/PackageTypes/GetPackageType', '套餐类型', 'demo-laypage3');

            // 表格加载完成后渲染 switch 组件
            form.on('switch(switchStatus)', function (obj) {
                var value = obj.elem.checked? 1 : 0;
                layer.msg('状态切换:'+ (value === 1? '开启' : '关闭'));
                // 在这里可以根据需要发送请求更新状态
            });

            // 选项卡切换事件
            tabs.on('tab(demoTabs1)', function (obj) {
                var layId = obj.elem.attr('lay-id');
                switch (layId) {
                    case 'aaa':
                        // 显示 Tab1 的表格，隐藏其他表格
                        $('#test1').show();
                        $('#test2').hide();
                        $('#test3').hide();
                        break;
                    case 'bbb':
                        // 显示 Tab2 的表格，隐藏其他表格
                        $('#test1').hide();
                        $('#test2').show();
                        $('#test3').hide();
                        break;
                    case 'ccc':
                        // 显示套餐类型的表格，隐藏其他表格
                        $('#test1').hide();
                        $('#test2').hide();
                        $('#test3').show();
                        break;
                }
            });

            // 为每个表格添加事件处理
            ['test1', 'test2', 'test3'].forEach(function (tableId) {
                // 工具栏事件
                table.on('toolbar(' + tableId + ')', function (obj) {
                    var id = obj.config.id;
                    var checkStatus = table.checkStatus(id);
                    var othis = lay(this);
                    switch (obj.event) {
                        case 'getCheckData':
                            var data = checkStatus.data;
                            layer.alert(layui.util.escape(JSON.stringify(data)));
                            break;
                        case 'getData':
                            var getData = table.getData(id);
                            console.log(getData);
                            layer.alert(layui.util.escape(JSON.stringify(getData)));
                            break;
                    };
                });

                // 表头自定义元素工具事件
                table.on('colTool(' + tableId + ')', function (obj) {
                    var event = obj.event;
                    console.log(obj);
                    if (event === 'email-tips') {
                        layer.alert(layui.util.escape(JSON.stringify(obj.col)), {
                            title: '当前列属性选项'
                        });
                    }
                });

                       table.on('tool(' + tableId + ')', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                // 编辑逻辑保持不变
            } else if (obj.event === 'delete') {
                if (tableId === 'test2') { // 判断是否是体检项目表格
                    layer.confirm('确定要删除该体检项目记录吗？', {
                        title: '删除确认',
                        btn: ['确定', '取消'],
                        shadeClose: false
                    }, function (index) {
                        var deleteUrl = 'https://localhost:7027/api/PhysicalExaminationItem/DeletedPhysicalExaminationItem?PhysicalExaminationItemsId=' + data.physicalExaminationItemsId;
                        fetch(deleteUrl, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            }
                        })
                           .then(response => {
                                if (!response.ok) {
                                    throw new Error('删除失败');
                                }
                                return response.json();
                            })
                           .then(data => {
                                obj.del();
                                layer.close(index);
                                layer.msg('删除成功');
                            })
                           .catch(error => {
                                layer.close(index);
                                layer.msg('删除失败: ' + error.message);
                                console.error('删除失败:', error);
                            });
                    }, function (index) {
                        layer.close(index);
                    });
                } else if (tableId === 'test3') { // 原套餐类型删除逻辑
                    layer.confirm('确定要删除该记录吗？', {
                        title: '删除确认',
                        btn: ['确定', '取消'],
                        shadeClose: false
                    }, function (index) {
                        var deleteUrl = 'https://localhost:7027/api/PackageTypes/DeletedPackageType?PackageTypeId=' + data.packageTypeId;
                        fetch(deleteUrl, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            }
                        })
                           .then(response => {
                                if (!response.ok) {
                                    throw new Error('删除失败');
                                }
                                return response.json();
                            })
                           .then(data => {
                                obj.del();
                                layer.close(index);
                                layer.msg('删除成功');
                            })
                           .catch(error => {
                                layer.close(index);
                                layer.msg('删除失败: ' + error.message);
                                console.error('删除失败:', error);
                            });
                    }, function (index) {
                        layer.close(index);
                    });
                } else if (tableId === 'test1') { // 新增针对体检套餐表格的删除逻辑
                    layer.confirm('确定要删除该体检套餐记录吗？', {
                        title: '删除确认',
                        btn: ['确定', '取消'],
                        shadeClose: false
                    }, function (index) {
                        var deleteUrl = 'https://localhost:7027/api/HealthCheckPackage/DeletedHealthCheckPackage?HealthCheckPackageId=' + data.healthCheckPackageId;
                        fetch(deleteUrl, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            }
                        })
                           .then(response => {
                                if (!response.ok) {
                                    throw new Error('删除失败');
                                }
                                return response.json();
                            })
                           .then(data => {
                                obj.del();
                                layer.close(index);
                                layer.msg('删除成功');
                            })
                           .catch(error => {
                                layer.close(index);
                                layer.msg('删除失败: ' + error.message);
                                console.error('删除失败:', error);
                            });
                    }, function (index) {
                        layer.close(index);
                    });
                }
            } else if (obj.event ==='more') {
                // 更多操作逻辑保持不变
            }
        });

                // table 滚动时移除内部弹出的元素
                var tableInst = table.getOptions(tableId);
                tableInst.elem.next().find('.layui-table-main').on('scroll', function () {
                    dropdown.close('dropdown-table-tool-' + tableId);
                });

                // 触发表格复选框选择
                table.on('checkbox(' + tableId + ')', function (obj) {
                    console.log(obj)
                });

                // 触发表格单选框选择
                table.on('radio(' + tableId + ')', function (obj) {
                    console.log(obj)
                });

                // 行单击事件
                table.on('row(' + tableId + ')', function (obj) {
                });

                // 行双击事件
                table.on('rowDouble(' + tableId + ')', function (obj) {
                    console.log(obj);
                });

                // 单元格编辑事件
                table.on('edit(' + tableId + ')', function (obj) {
                    var field = obj.field;
                    var value = obj.value;
                    var data = obj.data;
                    layer.msg('编辑成功', { icon: 1 });
                    var update = {};
                    update[field] = value;
                    obj.update(update);
                });
            });
        });
    </script>
</body>

</html>